package com.feishi.core.media.opencv;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-4-20 17:17
 **/

import com.feishi.core.media.opencv.util.OpenCvUtil;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import org.opencv.video.BackgroundSubtractorMOG2;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.util.ArrayList;
import java.util.List;

public class CameraBasic2 {

    static {
        OpenCvUtil.loadLibrary();
//        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    private JFrame frame;
    static JLabel label;
    static int flag = 0;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CameraBasic2 window = new CameraBasic2();
                    window.frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        VideoCapture camera = new VideoCapture();
        camera.open(0);

        if (!camera.isOpened()) {
            System.out.println("Camera Error");
        } else {
            Mat frame = new Mat();
            BackgroundSubtractorMOG2 bs = Video.createBackgroundSubtractorMOG2();
            bs.setHistory(100);
            Mat tmp = new Mat();

            while (flag == 0) {
                camera.read(frame);
                // 捕捉
//                bs.apply(frame, tmp, 0.1f);
//
//                List<MatOfPoint> contours = new ArrayList<>();
//                Mat hierarchy = new Mat();
//                Imgproc.findContours(tmp, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
//                Imgproc.dilate(tmp, tmp, new Mat(), new Point(-1, -1), 2);
//
//                for (MatOfPoint mf : contours) {
//                    if (Imgproc.contourArea(mf) < 1000) {
//                        continue;
//                    }
//                    // Imgproc.drawContours(frame, contours,
//                    // contours.indexOf(mf), new Scalar(0, 255, 255));
//                    Imgproc.fillConvexPoly(frame, mf, new Scalar(0, 255, 255));
//                    Rect r = Imgproc.boundingRect(mf);
//                    Imgproc.rectangle(frame, r.tl(), r.br(), new Scalar(0, 255, 0), 2);
//                    //Imgcodecs.imwrite("E:\\work\\qqq\\camera2\\" + "img" + System.currentTimeMillis() + ".jpg", frame);
//                }

                label.setIcon(new ImageIcon(matToBufferedImage(frame)));
                try {
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Create the application.
     */
    public CameraBasic2() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 800, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("\u62CD\u7167");
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                flag = 1;
            }
        });
        btnNewButton.setBounds(33, 13, 113, 27);
        frame.getContentPane().add(btnNewButton);

        label = new JLabel("");
        label.setBounds(0, 0, 800, 450);
        frame.getContentPane().add(label);
    }

    public static BufferedImage matToBufferedImage(Mat mat) {
        if (mat.height() > 0 && mat.width() > 0) {
            BufferedImage image = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR);
            WritableRaster raster = image.getRaster();
            DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
            byte[] data = dataBuffer.getData();
            mat.get(0, 0, data);
            return image;
        }

        return null;
    }
}
